package top.abrsm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import top.abrsm.entity.MessageEntity;
import top.abrsm.mapper.MessageMapper;
import top.abrsm.service.IMessageService;
import top.abrsm.util.StateEnum;
import top.abrsm.util.StateException;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Author: Wuzh
 * @Description:
 * @Date Created in 17:54 2022-10-16
 * @return
 */
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, MessageEntity> implements IMessageService {

    @Resource
    private MessageMapper messageMapper;

    @Override
    public List<MessageEntity> queryList ( MessageEntity messageEntity ) {
        if ( messageEntity == null ) {
            throw new StateException ( StateEnum.REQUEST_PARAM_EXCE );
        }
        List<MessageEntity> messageEntities = messageMapper.queryList ( messageEntity.getNotifierId (), messageEntity.getType (), ( messageEntity.getPageNum () - 1 ) * messageEntity.getPageSize (), messageEntity.getPageSize () );
        return messageEntities;
    }

    @Override
    public Integer queryCount ( MessageEntity messageEntity ) {
        Integer count = messageMapper.queryCount ( messageEntity.getNotifierId (), messageEntity.getType () );
        return count;
    }

    @Override
    public MessageEntity saveSingle ( MessageEntity messageEntity ) {
        if ( messageEntity == null ) {
            throw new StateException ( StateEnum.REQUEST_PARAM_EXCE );
        }
        if ( StringUtils.isBlank ( messageEntity.getId () ) ) {
            throw new StateException ( StateEnum.PRIMARY_NULL_EXCE );
        }
        messageEntity.setIsRead ( 0 );
        messageEntity.setCreateTime ( new Date () );
        int insert = baseMapper.insert ( messageEntity );
        if ( insert == 0 ) {
            throw new StateException ( StateEnum.INSERT_EXCE );
        }
        return messageEntity;
    }

    @Override
    public void updateSingle ( String notifierId ) {
        messageMapper.update ( notifierId );
    }

    @Override
    public Integer queryUnReader ( String notifierId ) {
        Integer integer = baseMapper.selectCount ( new QueryWrapper<MessageEntity> ().eq ( "notifierId", notifierId ).eq ( "isRead", 0 ) );
        return integer;
    }
}
